//
//  SMMultiTextField.m
//  testTextfield
//
//  Created by Jekin on 2018/11/16.
//  Copyright © 2018 Jekin. All rights reserved.
//

#import "SMMultiTextField.h"

@implementation SMMultiTextField {
    NSInteger _length;
}


- (void)awakeFromNib {
    [super awakeFromNib];
    self.forbiddenType = SMTextFunctionTypeAllFunction;
    self.maxNumber = INT_MAX;
    [self addTarget:self action:@selector(textDidEditChange:) forControlEvents:UIControlEventEditingChanged];
    self.delegate = self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {

        self.forbiddenType = SMTextFunctionTypeAllFunction;
        self.maxNumber = INT_MAX;
        [self addTarget:self action:@selector(textDidEditChange:) forControlEvents:UIControlEventEditingChanged];
        self.delegate = self;
    }
    return self;
}


- (void)textDidEditChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
//    UITextInputMode *inputMode = [UITextInputMode activeInputModes].firstObject;
    if (!position){//没有高亮选择
        if (toBeString.length > self.maxNumber && textField.markedTextRange == nil){
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:self.maxNumber];
            if (rangeIndex.length == 1){
                textField.text = [self resultString:[toBeString substringToIndex:self.maxNumber]];
            }
            else{
                textField.text = [self resultString:[toBeString substringWithRange:NSMakeRange(0, _length)]];
            }
        } else {
            textField.text = [self resultString:toBeString];
            _length = toBeString.length;
        }
    }else {//有高亮选择
        if (self.contentType == SMTextContentTypeOnlyNum) {
            textField.text = @"";
        }else if (self.contentType == SMTextContentTypeASCII){
            textField.text = [self filterOtherKeepASCWithString:toBeString];
        }                
    }
}


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (self.forbiddenType == SMTextFunctionTypeNoneFunction)return [super canPerformAction:action withSender:sender];
    if (self.forbiddenType == SMTextFunctionTypeAllFunction)return NO;
    if(action == @selector(paste:)){        
        return (self.forbiddenType & SMTextFunctionTypePaste) == 0;
    }
    if (action == @selector(selectAll:)) {
        return (self.forbiddenType &SMTextFunctionTypeSelectAll) == 0;
    }
    if (action == @selector(select:)) {
        return (self.forbiddenType & SMTextFunctionTypeSelectSignl) == 0;
    }
    return [super canPerformAction:action withSender:sender];
}

#pragma mark UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0)return YES;
    if ([self.filterCharactor containsObject:string])return NO;
    if (self.contentType == SMTextContentTypeDefalut)return YES;
    if (self.contentType == SMTextContentTypeOnlyNum) return [self validateNumber:string];
    if (self.contentType == SMTextContentTypeOnlyChinese) {
        //不可输入数字/以及特殊字符
        return ![self validateChinese:string]&&![self validateNumber:string];
    }
    return YES;
}


- (NSString *)resultString:(NSString *)string {
    switch (self.contentType) {

        case SMTextContentTypeASCII://(过滤中文)
            return [self filterOtherKeepASCWithString:string];
            break;
        case SMTextContentTypeDefalut:
            return string;
            break;
        case SMTextContentTypeOnlyNum:
            return [self filterOtherKeepNumberWithString:string];
            break;
        case SMTextContentTypeOnlyChinese:
            return [self filterOtherKeepChineseWithString:string];
            break;
        default:
            return string;
            break;
    }
    return string;
}
//过滤中文(只显示ASCII)
- (NSString *)filterOtherKeepASCWithString:(NSString *)string {
    return [self filterCharactor:string withRegex:@"[\u4e00-\u9fa5]"];
}

//过滤非数字字符(只显示数字)
- (NSString *)filterOtherKeepNumberWithString:(NSString *)string {
    return [self filterCharactor:string withRegex:@"[a-zA-Z\u4e00-\u9fa5]"];
}


//过滤非汉字字符(只显示中文)
- (NSString *)filterOtherKeepChineseWithString:(NSString *)string {
    return [self filterCharactor:string withRegex:@"[^\u4e00-\u9fa5]"];
}

//过滤指定字符
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *searchText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}



- (BOOL)validateNumber:(NSString*)string {
    BOOL isValid = YES;
    NSUInteger len = string.length;
    if (len > 0) {
        NSString *numberRegex = @"^[0-9]*$";
        NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
        isValid = [numberPredicate evaluateWithObject:string];
    }
    return isValid;
}
- (BOOL)validateChinese:(NSString *)string {
    BOOL isValid = YES;
    NSUInteger len = string.length;
    if (len > 0) {
        NSString *numberRegex = @"((?=[\\x00-\\xff]|。|、|“|”+)[^A-Za-z0-9])";
        NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
        isValid = [numberPredicate evaluateWithObject:string];
    }
    return isValid;
}


@end
